import Axios from 'axios'

let Root = null;
let Connect = null;
let Server = null;

export default {
  init,
  httpPost,
  httpGet
}

function init(vm) {
  Root = vm;
  Server = vm.$config.apiServer
  Connect = Axios.create({
    //timeout: 5000
  });
}

/**
 * POST/GET 请求
 * type: post/get
 * url: 接口
 * data: {
 * 		payload: Object参数（主要传参方式）,
 * 		params: URL参数,
 * 		headers: Object headers,
 * }
 * options: {
 * 		success: Function 成功后的回调,
 * 		error: Function 失败后的回调, 已统一处理错误提示，非特殊情况不要传（若传了且return true，则继续处理错误提示）
 * 		complete: Function 完成后的回调
 * }
 */

function _ajax(type, url, data, options) {
  /**
   * 如果不处理success，则返回 Promise 对象，axios 返回的promise策略过于简单
   * 通过 Promise.then/Promise.catch/Promise.finally 来分别替代 success/error/complete的回调
   * 可使用 async/await 替代 Promise.finally，让代码更加简洁
   */
  if (!(options && options.success)) {
    return new Promise((resolve, reject)=> {
      const _options = {
        success: resolve,
        error: (result)=> {
          reject(result)
          if (options && options.error) {
            return options.error(result)
          } else {
            return true //让 _ajax 继续处理错误信息
          }
        },
        netError: (result)=> {
          reject(result)
          if (options && options.netError) {
            return options.netError(result)
          } else {
            return true //让 _ajax 继续处理错误信息
          }
        }
      }
      _ajax(type, url, data, _options)
    })
  }
  
  if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
    url = Server + url;
  }

  let payload = null
  let params = {}
  let headers = {}

  //Parameters（URL传参）
  if (data && data.params) {
    params = data.params;
  }

  //headers
  if (data && data.headers) {
    headers = data.headers
  }

  //payload
  if (data && data.payload) {
    payload = data.payload;
  }
  
  const sendRequest = {
    post: ()=> Connect.post(url, payload, {params, headers}),
    get: ()=> Connect.get(url, {params, headers})
  }[type]

  sendRequest().then((response) => {
    try {
      let result = response.data;
      if (result === '') {
        return Root.$message.error('服务器无响应')
      }

      if (result.code) {

        if (result.code === 401) {
          Root.$message.info('未登录')
          return Root.$router.push('/login')
        }

        let isContinue = true;  //过滤之后是否继续执行“统一的错误信息提示”
        if (options.error) {
          isContinue = options.error(result);
        }
        if (isContinue) {
          Root.$message.error(result.msg)
        }

      } else {
        options.success && options.success(result)
      }
    } catch(e) {
      console.error(e)
    }
  })
  .catch((e) => {
    let isContinue = true;  //过滤之后是否继续执行“统一的错误信息提示”
    if (options.netError) {
      isContinue = options.netError(e);
    }
    if (isContinue) {
      Root.$message.error('网络连接失败')
    }
  })
  .finally(()=> {
    options.complete && options.complete();
  })
}

function httpPost(url, data, options) {
  return _ajax('post', url, data, options)
}

// 转 fromData
httpPost.__proto__.formData = (url, data, options)=> {
  if (data.payload) {
    const form = new FormData();
    const _toKeyValue = (data,parentKey)=> {
      for(let key in data){
        let _key = key;
        if(parentKey){
          _key = parentKey+'['+key+']';
        }
        if(data[key] && typeof data[key] == 'object' &&!(Object.prototype.toString.call(data[key]) !== '[object File]')){
          _toKeyValue(data[key],_key);
        } else {
          form.append(_key,data[key]);
        }
      }
    }
    _toKeyValue(data);
    data.payload = form
  }
  return httpPost(url, data, options)
}

function httpGet(url, data, options) {
  return _ajax('get', url, data, options)
}